<script setup lang="tsx" name="XtxTabs">
import { useSlots, VNode, provide, toRefs } from "vue";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});
//
const { modelValue } = toRefs(props);
provide("activeNameValue", modelValue);

const emit = defineEmits(["update:modelValue", "tab-click"]);
const slots = useSlots();

// 点击切换active
const clickFn = (item: VNode,index:number) => {
  console.log(item.props?.name);
  emit("update:modelValue", item.props?.name);
  emit("tab-click", {
    tab: item,
    index: index,
  });
};
// tsx函数
const Tab = () => {
  // #1
  const arr = (slots as any).default();
  // #2
  const panels: any[] = [];
  // #3
  arr.forEach((item: any) => {
    // 处理基本的写法，直接内部写 XtxTabsPanel
    if (item.type.name === "XtxTabsPanel") {
      panels.push(item);
    } else {
      // 处理 v-for 的情况
      if (item.children) {
        // 一个节点 => 7个panel
        item.children.forEach((panel: any) => {
          panels.push(panel);
        });
      }
    }
  });

  const navs = (
    <nav>
      {panels?.map((item: VNode, index: number) => (
        <a
          key={index}
          href="javascript:;"
          class={{ active: props.modelValue === item.props?.name }}
          onClick={() => clickFn(item,index)}
        >
          {item.props!.label}
        </a>
      ))}
    </nav>
  );
  return <div class="xtx-tabs">{[navs, panels]}</div>;
};
</script>
<template>
  <Tab />
</template>

<style lang="less">
.xtx-tabs {
  background: #fff;
  > nav {
    height: 60px;
    line-height: 60px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;
    > a {
      width: 110px;
      border-right: 1px solid #f5f5f5;
      text-align: center;
      font-size: 16px;
      &.active {
        border-top: 2px solid @xtxColor;
        height: 60px;
        background: #fff;
        line-height: 56px;
      }
    }
  }
}
</style>
